package netty.demo.nio.byteBuffer;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Zed
 * @description
 * @date 2022/10/20 21:21
 */
//FileChannel
@Slf4j
public class testByteBuffer {
    public static void main(String[] args) {
        /*
         * 获取FileChannel的方式
         * 1.输入输出流
         * 2.RandomAccessFile
         */
        try {
            FileChannel channel = new FileInputStream("data.txt").getChannel();
            //准备缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while (true) {
                //从channel读取数据，向Buffer写入
                int len = channel.read(buffer);
                log.debug("读取到的字节数:{}", len);
                if (len == -1) {//没有内容了
                    break;
                }
                //切换至读模式
                buffer.flip();
                while (buffer.hasRemaining()) {
                    byte b = buffer.get();
                    log.debug("实际的字节:{}", (char) b);
                }
                //切换为写模式
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
